/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.relaxng.simplification.normalization.patterns;

import java.util.List;

import moxl.dom.MoxlElement;
import moxl.dom.ethereal.EtherealElement;
import moxl.dom.mutable.MutableElement;
import moxl.relaxng.schema.RelaxNgSchemaElementType;

public class ZeroOrMoreTransformer
{
	public void transform(MutableElement parent, MutableElement child)
	{
		// zeroOrMore patterns are transformed into choice patterns between a oneOrMore pattern including their unique child pattern and an empty
		// pattern.
		List<? extends MoxlElement> children = child.getChildElements();
		if (children.size() != 1)
		{
			throw new IllegalStateException();
		}
		else
		{
			MoxlElement uniqueChildPatternEl = child.removeElement(0); // TODO: Create a test that checks for null status of removed node's parent after
			// removal
			MutableElement choiceEl = new EtherealElement(RelaxNgSchemaElementType.choice.getName());
			MutableElement oneOrMoreEl = new EtherealElement(RelaxNgSchemaElementType.oneOrMore.getName());

			oneOrMoreEl.addChild(uniqueChildPatternEl);
			choiceEl.addChild(oneOrMoreEl);

			MutableElement emptyEl = new EtherealElement(RelaxNgSchemaElementType.empty.getName());
			choiceEl.addChild(emptyEl);

			parent.replace(child, choiceEl);
		}
	}

}
